<template>
  <div class="safe-note-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-info">
          <h1 class="page-title">
            <el-icon><Lock /></el-icon>
            安全记事本
          </h1>
          <p class="page-description">安全加密的个人笔记管理工具</p>
        </div>
        <div class="header-stats">
          <div class="stat-item">
            <span class="stat-value">{{ dataList?.length || 0 }}</span>
            <span class="stat-label">总笔记</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ myNotesCount }}</span>
            <span class="stat-label">我的笔记</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar-section">
      <div class="toolbar-content">
        <div class="toolbar-left">
          <el-select v-model="note_type" @change="getDataList" class="type-select">
            <el-option key="0" label="全部" value="0" />
            <el-option key="1" label="我的" value="1" />
            <el-option key="2" label="公开" value="2" />
            <el-option key="3" label="他人分享我的" value="3" />
          </el-select>
          <el-input v-model="searchText" clearable class="search-input" placeholder="搜索笔记..." :prefix-icon="Search" />
        </div>
        <div class="toolbar-right">
          <el-button :icon="Refresh" @click="refreshData" title="刷新数据">刷新</el-button>
          <el-button :icon="Plus" type="primary" @click="openDrawer('新增', {})"> 新增笔记 </el-button>
        </div>
      </div>
    </div>

    <!-- 笔记列表 -->
    <div class="notes-grid">
      <div v-for="(item, index) in dataList" :key="index" class="note-card" @click="openView(item)">
        <div class="note-header">
          <div class="note-title">
            <el-icon v-if="item.password" class="lock-icon"><Lock /></el-icon>
            <span class="title-text" :title="item.name">{{ item.name }}</span>
          </div>
          <el-dropdown trigger="click" @command="handleCommand" @click.stop>
            <el-button circle size="small" text class="more-btn" @click.stop>
              <el-icon><More /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-if="userUser.userInfo._id === item.create_user" :command="{ name: 'edit', item: item }">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-dropdown-item>
                <el-dropdown-item v-if="userUser.userInfo._id === item.create_user" :command="{ name: 'delete', item: item }">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-dropdown-item>
                <el-dropdown-item :command="{ name: 'view', item: item }">
                  <el-icon><View /></el-icon>
                  查看
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <div class="note-content">
          <div class="note-stats">
            <div class="stat-row">
              <div class="stat-item">
                <el-icon><Document /></el-icon>
                <span>{{ item.size }} 字</span>
              </div>
              <div class="stat-item">
                <el-icon><User /></el-icon>
                <span>{{ userNameRender(item.create_user, userList) }}</span>
              </div>
            </div>
            <div class="stat-row">
              <div class="stat-item">
                <el-icon><Clock /></el-icon>
                <span>{{ useDateFormat(item.last_use, "MM-DD HH:mm").value }}</span>
              </div>
              <div class="stat-item">
                <el-icon><Pointer /></el-icon>
                <span>{{ item.clickCount }} 次浏览</span>
              </div>
            </div>
          </div>
        </div>

        <div class="note-footer">
          <el-tag v-if="item.open" size="small" type="success">公开</el-tag>
          <el-tag v-else-if="isSharedNote(item)" size="small" type="primary">部分人可见</el-tag>
          <el-tag v-else size="small" type="info">私密</el-tag>
          <el-tag v-if="item.password" size="small" type="warning">加密</el-tag>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!dataList || dataList.length === 0" class="empty-state">
        <el-empty description="暂无笔记">
          <el-button type="primary" @click="openDrawer('新增', {})"> 创建第一个笔记 </el-button>
        </el-empty>
      </div>
    </div>

    <el-backtop :right="100" :bottom="100" />
    <DetailDrawer ref="drawerRef" />

    <!-- 查看笔记弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      width="70%"
      top="5vh"
      :title="noteName"
      class="note-dialog"
    >
      <div class="note-view-content" v-html="content"></div>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 密码验证弹窗 -->
    <el-dialog
      v-model="password_dialogVisible"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="400px"
      top="30vh"
      title="密码验证"
      class="password-dialog"
    >
      <div class="password-form">
        <el-input
          size="large"
          v-model="valid_password"
          placeholder="请输入密码"
          clearable
          type="password"
          show-password
          autocomplete="new-password"
          @keyup.enter="onPasswordValid"
        >
          <template #prefix>
            <el-icon><Lock /></el-icon>
          </template>
        </el-input>
      </div>
      <template #footer>
        <el-button @click="password_dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onPasswordValid">验证</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { computed, onMounted, reactive, ref } from "vue";
import { Plus, Search, More, Pointer, User, Document, Clock, Lock, Edit, Delete, View, Refresh } from "@element-plus/icons-vue";
import { useDateFormat } from "@vueuse/core";
import DetailDrawer from "./detailDrawer.vue";
import { SafeNote } from "@/api/types/base";
import apiService from "@/api/services/apiService";
import { useHandleData } from "@/hooks/useHandleData";
import { useDataStore } from "@/stores/modules/data";
import { userNameRender } from "@/hooks/useTextRender";
import { decryptData, encryptData } from "@/api/services/security";
import { useUserStore } from "@/stores/modules/user";
import { ElMessage } from "element-plus";
import { watch } from "vue";
import { useTimeoutFn, useMouse, onKeyStroke } from "@vueuse/core";

const initVar = reactive({
  tbName: "safeNote",
  tbCnName: "安全记事本"
});

const dataStore = useDataStore();
const userUser = useUserStore();
const dialogVisible = ref(false);
const password_dialogVisible = ref(false);
const noteName = ref("");
const content = ref("");
const valid_password = ref("");
const curNote = ref();
const searchText = ref();
const note_type = ref("0");
const passwordValidType = ref("view");
const userList = computed(() => dataStore.userList);

// 计算我的笔记数量
const myNotesCount = computed(() => {
  return dataList.value?.filter(item => item.create_user === userUser.userInfo._id).length || 0;
});

// 判断是否为共享笔记（有共享用户但不是公开）
const isSharedNote = (item: SafeNote) => {
  return !item.open && item.sharedUsers && item.sharedUsers.length > 0;
};

const drawerRef = ref<InstanceType<typeof DetailDrawer> | null>(null);

// 监听长时间未操作，关闭弹窗
const timeout = 20000; // 20秒
const isInactive = ref(false);
const { x, y } = useMouse();
const handleInactive = () => {
  isInactive.value = true;
  dialogVisible.value = false;
  drawerRef.value?.closeDialog();
  password_dialogVisible.value = false;
  ElMessage.warning("安全考虑，20秒内未操作关闭弹窗。");
};
const { start, stop } = useTimeoutFn(handleInactive, timeout, { immediate: false });

// 重置计时器的函数
const resetTimer = () => {
  isInactive.value = false;
  stop();
  start();
};

// 监听鼠标移动重置计时器
watch(
  [x, y],
  () => {
    console.log("move");
    resetTimer();
  },
  { immediate: true }
);

// 监听键盘输入重置计时器（监听所有按键）
onKeyStroke(true, () => {
  console.log("keystroke");
  resetTimer();
});

onMounted(() => {
  dataStore.findUserList();
  getDataList();
});

const dataList = ref<SafeNote[]>();

watch(searchText, () => {
  getDataList();
});

const getDataList = async () => {
  let noteTypeCondition;
  if (note_type.value === "0") {
    // 全部：我的、公开的、他人分享给我的
    noteTypeCondition = {
      $or: [{ create_user: userUser.userInfo._id }, { open: true }, { sharedUsers: { $in: [userUser.userInfo._id] } }]
    };
  } else if (note_type.value === "1") {
    // 我的：我创建的
    noteTypeCondition = { create_user: userUser.userInfo._id };
  } else if (note_type.value === "2") {
    // 公开：非我创建的公开笔记
    noteTypeCondition = { $and: [{ create_user: { $ne: userUser.userInfo._id } }, { open: true }] };
  } else if (note_type.value === "3") {
    // 他人分享我的：非我创建但分享给我的
    noteTypeCondition = {
      $and: [{ create_user: { $ne: userUser.userInfo._id } }, { sharedUsers: { $in: [userUser.userInfo._id] } }]
    };
  }

  const condition = {
    $and: [{ like: { name: searchText.value } }, noteTypeCondition]
  };

  const options = {
    fields: ["_id", "name", "size", "open", "password", "last_use", "create_at", "create_user", "clickCount", "sharedUsers"],
    sort: {
      clickCount: -1,
      last_use: -1
    }
  };

  let { data } = await apiService.find<SafeNote[]>(initVar.tbName, condition, options);
  dataList.value = data;
};

const handleCommand = command => {
  if (command.name === "edit") {
    passwordValidType.value = "edit";
    valid_password.value = "";
    password_dialogVisible.value = true;
    curNote.value = command.item;
  } else if (command.name === "delete") {
    deleteAccount(command.item);
  } else if (command.name === "view") {
    openView(command.item);
  }
};

const onPasswordValid = () => {
  if (valid_password.value) {
    if (encryptData(valid_password.value) === curNote.value.password) {
      password_dialogVisible.value = false;
      if (passwordValidType.value === "view") {
        noteView(curNote.value);
      } else if (passwordValidType.value === "edit") {
        if (curNote.value) {
          openDrawer("编辑", curNote.value);
        }
      }
    } else {
      ElMessage.info("密码错误");
    }
  } else {
    ElMessage.info("请输入密码");
  }
};

const openView = async item => {
  curNote.value = item;
  content.value = "";
  noteName.value = "";
  valid_password.value = "";

  if (item.password) {
    passwordValidType.value = "view";
    valid_password.value = "";
    password_dialogVisible.value = true;
    start(); // 启动安全计时器
  } else {
    noteView(item);
  }
};

const noteView = async item => {
  const curNote = await apiService.findOne<SafeNote>(initVar.tbName, { _id: item._id });
  if (curNote) {
    if (curNote.data.content) {
      content.value = decryptData(curNote.data.content);
    }
    noteName.value = curNote.data.name;

    dialogVisible.value = true;
    start(); // 启动安全计时器
    if (!item.clickCount) {
      item.clickCount = 0;
    }
    let updateData = {
      _id: item._id,
      clickCount: item.clickCount + 1,
      last_use: new Date()
    };
    await apiService.updateById(initVar.tbName, updateData);
    item.clickCount = updateData.clickCount;
    item.last_use = updateData.last_use;
  }
};

// 刷新数据
const refreshData = async () => {
  try {
    // 重新加载用户列表和笔记数据
    await dataStore.findUserList();
    await getDataList();
    ElMessage.success("数据刷新成功");
  } catch (error) {
    console.error("刷新数据失败:", error);
    ElMessage.error("数据刷新失败");
  }
};

// 删除
const deleteAccount = async (params: SafeNote) => {
  await useHandleData(apiService.deleteById, initVar.tbName, params._id, `删除记事本【${params.name}】`);
  getDataList();
};

// 打开 drawer(新增、查看、编辑)
const openDrawer = (title: string, row: Partial<SafeNote> = {}) => {
  const params = {
    title,
    tbName: initVar.tbName,
    isView: title === "查看",
    row: row,
    api: title.indexOf("新增") !== -1 ? apiService.save : title === "编辑" ? apiService.updateById : undefined,
    getTableList: getDataList
  };
  drawerRef.value?.acceptParams(params);
};
</script>

<style lang="scss" scoped>
.safe-note-page {
  min-height: 100vh;
  padding: 10px;
  background: var(--el-bg-color-page);
}

// 页面头部
.page-header {
  position: relative;
  padding: 30px;
  margin-bottom: 24px;
  overflow: hidden;
  color: white;
  background: linear-gradient(135deg, var(--el-color-primary) 0%, var(--el-color-primary-light-3) 100%);
  border-radius: 12px;
  .header-content {
    position: relative;
    z-index: 2;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .header-info {
      .page-title {
        display: flex;
        gap: 12px;
        align-items: center;
        margin: 0 0 8px;
        font-size: 28px;
        font-weight: 600;
        color: white;
        .el-icon {
          font-size: 32px;
        }
      }
      .page-description {
        margin: 0;
        font-size: 16px;
        color: rgb(255 255 255 / 80%);
      }
    }
    .header-stats {
      display: flex;
      gap: 30px;
      .stat-item {
        text-align: center;
        .stat-value {
          display: block;
          font-size: 24px;
          font-weight: 700;
          color: white;
        }
        .stat-label {
          display: block;
          margin-top: 4px;
          font-size: 14px;
          color: rgb(255 255 255 / 80%);
        }
      }
    }
  }
}

// 工具栏
.toolbar-section {
  margin-bottom: 24px;
  .toolbar-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px;
    background-color: var(--el-bg-color);
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 12px;
    box-shadow: 0 2px 12px rgb(0 0 0 / 10%);
    .toolbar-left {
      display: flex;
      gap: 16px;
      align-items: center;
      .type-select {
        width: 140px;
      }
      .search-input {
        width: 280px;
      }
    }
    .toolbar-right {
      display: flex;
      gap: 12px;
      align-items: center;
    }
  }
}

// 笔记网格
.notes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  .note-card {
    position: relative;
    padding: 20px;
    cursor: pointer;
    background-color: var(--el-bg-color);
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 12px;
    box-shadow: 0 2px 12px rgb(0 0 0 / 10%);
    transition: all 0.3s ease;
    &:hover {
      border-color: var(--el-color-primary-light-7);
      box-shadow: 0 4px 20px rgb(0 0 0 / 15%);
      transform: translateY(-2px);
    }
    .note-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;
      .note-title {
        display: flex;
        flex: 1;
        gap: 8px;
        align-items: center;
        min-width: 0;
        .lock-icon {
          flex-shrink: 0;
          color: var(--el-color-warning);
        }
        .title-text {
          overflow: hidden;
          font-size: 16px;
          font-weight: 600;
          color: var(--el-text-color-primary);
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      .more-btn {
        color: var(--el-text-color-placeholder);
        &:hover {
          color: var(--el-color-primary);
        }
      }
    }
    .note-content {
      margin-bottom: 16px;
      .note-stats {
        .stat-row {
          display: flex;
          justify-content: space-between;
          margin-bottom: 8px;
          &:last-child {
            margin-bottom: 0;
          }
          .stat-item {
            display: flex;
            gap: 6px;
            align-items: center;
            font-size: 13px;
            color: var(--el-text-color-regular);
            .el-icon {
              font-size: 14px;
              color: var(--el-color-primary);
            }
          }
        }
      }
    }
    .note-footer {
      display: flex;
      gap: 8px;
      align-items: center;
      padding-top: 12px;
      border-top: 1px solid var(--el-border-color-lighter);
    }
  }
}

// 空状态
.empty-state {
  grid-column: 1 / -1;
  padding: 60px 20px;
  text-align: center;
}

// 弹窗样式
.note-dialog {
  .note-view-content {
    max-height: 70vh;
    padding: 20px;
    overflow-y: auto;
    background: var(--el-bg-color-page);
    border-radius: 8px;
    :deep(h1),
    :deep(h2),
    :deep(h3),
    :deep(h4),
    :deep(h5),
    :deep(h6) {
      color: var(--el-text-color-primary);
    }
    :deep(p) {
      margin-bottom: 12px;
      line-height: 1.6;
    }
  }
}
.password-dialog {
  .password-form {
    padding: 20px 0;
  }
}

// 响应式设计
@media (width <= 768px) {
  .safe-note-page {
    padding: 16px;
  }
  .page-header {
    padding: 20px;
    .header-content {
      flex-direction: column;
      gap: 20px;
      text-align: center;
      .header-stats {
        justify-content: center;
      }
    }
  }
  .toolbar-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    .toolbar-left {
      flex-direction: column;
      gap: 12px;
      .type-select,
      .search-input {
        width: 100%;
      }
    }
  }
  .notes-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}

@media (width <= 480px) {
  .notes-grid {
    .note-card {
      padding: 16px;
      .note-content .note-stats .stat-row {
        flex-direction: column;
        gap: 8px;
        align-items: flex-start;
      }
    }
  }
}
</style>
